package com.zhang.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhangshuaiyin
 * @date 2021-06-22 17:05
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {
    /**
     * 下划线
     */
    private static final String LINE = "_";
    /**
     * 空字符
     */
    private static final char CHAR_EMPTY = '\0';
    /**
     * 0
     */
    private static final String ZERO = "0";

    private static final Pattern LINE_PATTERN = Pattern.compile("_(\\w)");
    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");

    public static void main(String[] args) {
        String line = "object_dto";
        String hump = "objectDto";
        System.out.println(lineToHump(line));
        System.out.println(humpToLine(hump));
    }

    /**
     * 下划线转驼峰
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = LINE_PATTERN.matcher(str);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(buffer, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(buffer);
        return buffer.toString();
    }

    /**
     * 驼峰转下划线
     */
    public static String humpToLine(String str) {
        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(buffer, LINE + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(buffer);
        return buffer.toString();
    }

    /**
     * 不满位数，左补0操作
     *
     * @param str    目标字符串
     * @param length 要求位数
     * @return String
     */
    public static String leftPadZero(String str, int length) {
        if (str == null) {
            return "";
        }

        if (str.length() >= length) {
            return str;
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length - str.length(); i++) {
            builder.append(ZERO);
        }
        builder.append(str);
        return builder.toString();
    }

    /**
     * 不满位数，右补0操作
     *
     * @param str    目标字符串
     * @param length 要求位数
     * @return String
     */
    public static String rightPadZero(String str, int length) {
        if (str == null) {
            return "";
        }

        if (str.length() >= length) {
            return str;
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length - str.length(); i++) {
            builder.append(ZERO);
        }
        return str.concat(builder.toString());
    }
}
